package com.ltg.framework.util.pdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * <p> ClassName: PdfUtil </p>
 * <p> Package: com.ltg.framework.util </p>
 * <p> Description: </p>
 * <p></p>
 *
 * @Author: LTG
 * @Create: 2023/2/2 - 14:33
 * @Version: v1.0
 */
public class PdfUtil {

    public static void addWatermark(ByteArrayOutputStream outputStream, String text) {
        try {
            PdfReader reader = new PdfReader(outputStream.toByteArray());
            PdfStamper stamper = null;
            stamper = new PdfStamper(reader, outputStream);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
                float x = pageRect.getWidth() / 2;
                float y = pageRect.getHeight() / 2;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.8
                gs.setFillOpacity(0.8f);
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 40);
                under.setColorFill(BaseColor.GRAY);
                // 水印文字成45度角倾斜
                under.showTextAligned(Element.ALIGN_CENTER, text, x, y, 45);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
                under.restoreState();
            }
            stamper.close();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //这里的字体设置比较关键，这个设置是支持中文的写法
    }
}
